#include <iostream>
#include <string>
#include <cstring>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>

void Usage(std::string proc) // 使用手册
{
    std::cout << "Usage: " << proc << " clientip clientport" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "create socket error" << std::endl;
        return 0;
    }
    // client不需要程序员自己手动bind，系统会自动bind
    // 原因: 不同进程的端口号不同，为了避免进程间发生冲突，client就交由系统随机bind端口号
    
    //获取服务端socket
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    while (true)
    {
        std::cout << "Please Enter@ ";
        std::string line;
        std::getline(std::cin, line);

        //写给服务端
        sendto(sockfd, line.c_str(), line.size(), 0,
         (struct sockaddr*)&server, sizeof(server));

        //从服务端读
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        char buffer[1024];       
        int m = recvfrom(sockfd, buffer, sizeof(buffer), 0, 
         (struct sockaddr*)&tmp, &len);
        if(m > 0)
        {
            buffer[m] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}